package com.bear.atlassianmcp.confluence.mcp.tools;

import com.bear.atlassianmcp.confluence.model.ConfluenceLabel;
import com.bear.atlassianmcp.confluence.service.ConfluenceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Confluence标签管理MCP工具
 * 提供标签添加、查询等功能
 */
@Service
public class ConfluenceLabelTools {

    private static final Logger logger = LoggerFactory.getLogger(ConfluenceLabelTools.class);

    private final ConfluenceService confluenceService;

    @Autowired
    public ConfluenceLabelTools(ConfluenceService confluenceService) {
        this.confluenceService = confluenceService;
    }

    /**
     * 添加页面标签
     * 
     * @param pageId 页面ID
     * @param labelName 标签名称
     * @return 添加标签结果的格式化文本
     */
    // @Tool(description = "为指定的Confluence页面添加标签")
    public String addLabel(String pageId, String labelName, ToolContext toolContext) {
        logger.info("MCP Tool: Adding label '{}' to Confluence page {}", labelName, pageId);
        
        try {
            String result = confluenceService.addLabel(pageId, labelName, toolContext);
            
            StringBuilder response = new StringBuilder();
            response.append("✅ ").append(result).append("\n");
            response.append(String.format("🏷️ 已为页面 %s 添加标签: %s", pageId, labelName));
            
            logger.info("Successfully added label '{}' to Confluence page {} via MCP", labelName, pageId);
            return response.toString();
            
        } catch (Exception e) {
            logger.error("Failed to add label '{}' to Confluence page {} via MCP: {}", labelName, pageId, e.getMessage());
            return "❌ 添加标签失败。原因：" + e.getMessage() + 
                   "\n💡 请检查页面ID是否正确，以及是否有添加标签的权限。";
        }
    }

    /**
     * 获取页面标签列表
     * 
     * @param pageId 页面ID
     * @return 页面标签列表的格式化文本
     */
    // @Tool(description = "获取指定Confluence页面的所有标签列表")
    public String getPageLabels(String pageId, ToolContext toolContext) {
        logger.info("MCP Tool: Getting labels for Confluence page {}", pageId);
        
        try {
            List<ConfluenceLabel> labels = confluenceService.getPageLabels(pageId, toolContext);
            
            if (labels.isEmpty()) {
                return String.format("🏷️ 页面 %s 当前没有标签。", pageId);
            }
            
            StringBuilder result = new StringBuilder();
            result.append(String.format("🏷️ 页面 %s 的标签列表 (共%d个)：\n\n", pageId, labels.size()));
            
            for (int i = 0; i < labels.size(); i++) {
                ConfluenceLabel label = labels.get(i);
                result.append(String.format("%d. ", i + 1));
                result.append(label.toFormattedString());
                result.append("\n");
            }
            
            logger.info("Successfully retrieved {} labels for page {} via MCP", labels.size(), pageId);
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to get labels for page {} via MCP: {}", pageId, e.getMessage());
            return "❌ 获取页面标签失败。原因：" + e.getMessage();
        }
    }

    /**
     * 获取页面标签统计
     * 
     * @param pageId 页面ID
     * @return 页面标签统计信息
     */
    // @Tool(description = "获取指定Confluence页面的标签统计信息")
    public String getPageLabelStatistics(String pageId, ToolContext toolContext) {
        logger.info("MCP Tool: Getting label statistics for Confluence page {}", pageId);
        
        try {
            List<ConfluenceLabel> labels = confluenceService.getPageLabels(pageId, toolContext);
            
            StringBuilder result = new StringBuilder();
            result.append(String.format("📊 页面 %s 的标签统计：\n\n", pageId));
            result.append(String.format("🏷️ 标签总数: %d\n", labels.size()));
            
            if (!labels.isEmpty()) {
                result.append("\n🔍 标签列表:\n");
                for (ConfluenceLabel label : labels) {
                    result.append(String.format("• %s", label.getName()));
                    if (label.getPrefix() != null && !label.getPrefix().trim().isEmpty()) {
                        result.append(String.format(" (%s)", label.getPrefix()));
                    }
                    result.append("\n");
                }
            }
            
            logger.info("Successfully retrieved label statistics for page {} via MCP", pageId);
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to get label statistics for page {} via MCP: {}", pageId, e.getMessage());
            return "❌ 获取标签统计失败。原因：" + e.getMessage();
        }
    }

    /**
     * 批量添加标签
     * 
     * @param pageId 页面ID
     * @param labelNames 标签名称列表，用逗号分隔
     * @return 批量添加标签结果的格式化文本
     */
    // @Tool(description = "为指定的Confluence页面批量添加多个标签，标签名称用逗号分隔")
    public String addMultipleLabels(String pageId, String labelNames, ToolContext toolContext) {
        logger.info("MCP Tool: Adding multiple labels to Confluence page {}", pageId);
        
        try {
            String[] labels = labelNames.split(",");
            StringBuilder result = new StringBuilder();
            result.append(String.format("🏷️ 为页面 %s 批量添加标签：\n\n", pageId));
            
            int successCount = 0;
            int failCount = 0;
            
            for (String labelName : labels) {
                String trimmedLabel = labelName.trim();
                if (!trimmedLabel.isEmpty()) {
                    try {
                        confluenceService.addLabel(pageId, trimmedLabel, toolContext);
                        result.append(String.format("✅ %s - 添加成功\n", trimmedLabel));
                        successCount++;
                    } catch (Exception e) {
                        result.append(String.format("❌ %s - 添加失败: %s\n", trimmedLabel, e.getMessage()));
                        failCount++;
                    }
                }
            }
            
            result.append(String.format("\n📊 添加结果: 成功 %d 个，失败 %d 个", successCount, failCount));
            
            logger.info("Successfully added {} labels to Confluence page {} via MCP", successCount, pageId);
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to add multiple labels to Confluence page {} via MCP: {}", pageId, e.getMessage());
            return "❌ 批量添加标签失败。原因：" + e.getMessage();
        }
    }
}
